<template>
  <div>
    <div style="text-align: center">

      <el-upload
          ref="upload"
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
      >
        <el-avatar v-if="base64Avatar" :src="base64Avatar" class="avatar" />
        <el-avatar v-else
                   v-bind:style="{cursor:'pointer'}"
                   style="width: 120px;
                   height: 120px"
                   fit="fit"
                   src="/images/avatar.jpeg"/>
      </el-upload>

    </div>
    <div style="margin-top: 5vh">
      <el-row justify="center">
        <el-text>uid:{{ uid }}</el-text>
      </el-row>

      <el-row justify="center">
        <el-text>用户名:{{ userName }}</el-text>
      </el-row>

      <el-row justify="center">
        <el-text v-if="userPro==null">
          这个人很懒，还没有写简介喔
        </el-text>
        <el-text v-else>
          {{ userPro }}
        </el-text>
      </el-row>

    </div>

  </div>
</template>

<script setup>

import {onMounted, ref} from "vue";
import {getWithToken, postWithToken} from "@/net/postAndGetMethodWithToken";
import {ElMessage} from "element-plus";
import axios from "axios";

const uploadRef = ref(null)
const changeAvatar = () => {
  alert("change your Avatar")
}


const uid = ref(null)
const userName = ref(null)
const userPro = ref(null)

getWithToken("/api/user/info", (data, code, message) => {
  uid.value = data.uid
  userName.value = data.userName
  userPro.value = data.userProfile
})


const handleAvatarSuccess = (response, file, fileList) => {

}
const beforeAvatarUpload = async (file) => {
  if (!file) {
    ElMessage.error('No file selected!')
    return false
  }
  const isJpg = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJpg) {
    ElMessage.error('Avatar picture must be JPG format!')
  }
  if (!isLt2M) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
  }
  if (isJpg && isLt2M) {
    const formData = new FormData()
    formData.append('file', file)
    const response = await axios.post('/api/avatar/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'jwtToken': localStorage.getItem('token')
      }
    })
    if (response.data.code === 200) {
      ElMessage.success('上传成功')
      location.reload()
      return true
    } else {
      ElMessage.error('Upload failed')
      return false
    }
  } else {
    return false
  }
}
const base64Avatar = ref('')
onMounted(async () => {
  getWithToken('/api/avatar/download',
      (data,code,message)=>{
    base64Avatar.value = data
  },() =>{return false})
})
</script>

<style scoped>
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

</style>